/*

*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "DarberIpfs.h"
#include "ctl_ex.h"

// 暂时用数组做
/*	2023.12.4
	真是报应，马上就要解决这个问题，数组指针 和 指针数组
	明白了，问题不在于 数组和指针谁打谁
	主要是，除错了

	所以怎么定义呢？

	还是不对

	真他娘的作孽...一大把年纪了，居然还因为这种操蛋问题犯低级错误，需要调半天，才想起来问题所在.....
	这当然不能sizeof来除了，凑~~~
	不过，具体要怎么搞呢，我得想想
*/

// 这个方法比较蠢，当然有好一点的办法
// 比如说，"end"
static char *gateway[100] = 
{
	"ipfs.io",							
	"dweb.link",
	"gateway.ipfs.io",
	"ninetailed.ninja",
	"via0.com",
	"ipfs.eternum.io",
	"hardbin.com",
	"cloudflare-ipfs.com",
	"astyanax.io",
	"cf-ipfs.com",										// 10
	"ipns.co",
	"gateway.originprotocol.com",
	"gateway.pinata.cloud",
	"ipfs.sloppyta.co",
	"ipfs.busy.org",
	"ipfs.greyh.at",
	"gateway.serph.network",
	"jorropo.net",              // DNS都解析不出来，fuck
	"ipfs.fooock.com",
	"cdn.cwinfo.net",									// 20
	"aragon.ventures",
	"permaweb.io",
	"ipfs.best-practice.se",
	"storjipfs-gateway.com",
	"ipfs.runfission.com",
	"ipfs.trusti.id",
	"ipfs.overpi.com",
	"ipfs.ink",
	"ipfsgateway.makersplace.com",
	"ipfs.funnychain.co",								// 30
	"ipfs.telos.miami",
	"ipfs.mttk.net",
	"ipfs.fleek.co",
	"ipfs.jbb.one",
	"ipfs.yt",
	"hashnews.k1ic.com",
	"ipfs.drink.cafe",
	"ipfs.kavin.rocks",
	"ipfs.denarius.io",
	"crustwebsites.net",								// 40
	"ipfs0.sjc.cloudsigma.com",
	"ipfs.genenetwork.org",
	"ipfs.eth.aragon.network",
	"ipfs.smartholdem.io",
	"ipfs.xoqq.ch",
	"natoboram.mynetgear.com:8080",
	"video.oneloveipfs.com",
	"ipfs.anonymize.com",
	"ipfs.scalaproject.io",
	"search.ipfsgate.com",								// 50
	"ipfs.decoo.io",
	"alexdav.id",
	"ipfs.uploads.nu",
	"hub.textile.io",
	"ipfs1.pixura.io",
	"ravencoinipfs-gateway.com",
	"konubinix.eu",
	"ipfs.tubby.cloud",
	"ipfs.lain.la",
	"ipfs.kaleido.art",									// 60
	"ipfs.slang.cx",
	"ipfs.arching-kaos.com",
	"storry.tv",
	"ipfs.1-2.dev",
	"dweb.eu.org",
	"permaweb.eu.org",
	"ipfs.namebase.io",
	"ipfs.tribecap.co",
	"ipfs.kinematiks.com",
	"c4rex.co",											// 70
	"nftstorage.link",
	"gravity.jup.io",
	"fzdqwfb5ml56oadins5jpuhe6ki6bk33umri35p5kt2tue4fpws5efid.onion",
	"tth-ipfs.com",
	"ipfs.chisdealhd.co.uk",
	"ipfs.alloyxuast.tk",
	"ipfs.litnet.work",
	"4everland.io",
	"ipfs-gateway.cloud",
	"w3s.link",											// 80	
	"cthd.icu",
	"ipfs.joaoleitao.org",
	"ipfs.tayfundogdas.me",
	"ipfs.jpu.jp",
	"",													// means end
}; 

/*	
	获取5个连接最快的网关；
	然后分别连接，16个线程
	因为才5个，我他娘的也不考虑什么算法了
*/
#define MAX_FASTER_GATEWAY 5
#define MAX_CONNECT_THREAD 16

typedef struct s_gateway_time
{
	uint8_t pos;
	uint32_t in_us;
}st_gateway_time_record;

static st_gateway_time_record s_gateway_record[MAX_FASTER_GATEWAY];
static uint8_t s_count = 0;

// 只要存下最快的5个，其顺序不重要
// 首先写入最初5个，然后每次读入一个新的，逐一比较，小就留下，同时浮起大的，继续往后比较
static void faster_gateway_reset(void)
{
	s_count = 0;
}

static void top_faster_gateway(void)
{
	int i;

	if(0 == s_count)
		printf("all gateway unconnect!!!\n");

	for(i = 0;i < s_count;i++)
		printf("%d:\t%u\t%s\n",i,s_gateway_record[i].in_us,gateway[s_gateway_record[i].pos]);
}

static void insert_5_faster_gateway(uint8_t pos,uint32_t time)
{
	uint8_t i;
	st_gateway_time_record tmp,x;

	if(s_count < MAX_FASTER_GATEWAY)
	{
		s_gateway_record[s_count].pos = pos;
		s_gateway_record[s_count].in_us = time;
		s_count++;
		return;
	}

	x.in_us = time;
	x.pos = pos;

	for(i = 0;i < s_count;i++)
	{
		if(x.in_us < s_gateway_record[i].in_us)
		{
			tmp.in_us = s_gateway_record[i].in_us;
			tmp.pos = s_gateway_record[i].pos;

			s_gateway_record[i].in_us = x.in_us;
			s_gateway_record[i].pos = x.pos;

			x.in_us = tmp.in_us;
			x.pos = tmp.pos;
		}
	}
}

// in us
static uint32_t get_tcping_in_us(char *str)
{
	#define AVR_STR "Average = "
	double avg_time;
	char *p,*q;

	p = strstr(str,AVR_STR);
	if(NULL == p)
		return -1;

	p += strlen(AVR_STR);
	q = strstr(p,"ms");
	if(NULL == q)
		return -1;

	*q = '\0';
	avg_time = atof(p);

	return (uint32_t)(avg_time * 1000);
} 

// test trap
void test_top5_compare(void)
{
	int i;
	uint32_t s[] = {267563,465672,55453,34323,24322,24712,5713,52,734,3234,2442,4522,33224,433324,3333,233,573};
	int count;

	count = sizeof(s)/sizeof(uint32_t);

	faster_gateway_reset();
	for(i = 0;i < count;i++)
	{
		insert_5_faster_gateway(i,s[i]);
	}

	top_faster_gateway();
}

void test_gateway_connect_time(void)
{
    char cmd[100];
    size_t i,count;
    char out[512];
    char *pAvg;

	faster_gateway_reset();

    count = sizeof(gateway)/(sizeof(char)*100);

	i = 0;
    while(0 != strlen(gateway[i]))
    {
        cmd[0] = '\0';
        strcpy(cmd,"tcping ");
        strcat(cmd,gateway[i]);
        ctl_cmd(cmd,out);
        pAvg = strstr(out,"Minimum");
        if(NULL != pAvg)
		{
			uint32_t avg;

			//printf("%s",pAvg);
            avg = get_tcping_in_us(pAvg);
			//printf("%d\t%d\n",i,avg);
			insert_5_faster_gateway(i,avg);
		}

        pAvg = strstr(out,"Was unable to connect");
        // if(NULL != pAvg)
        //     printf("%d:\t%s",i,pAvg);     

        pAvg = strstr(out,"DNS: Could not find host");
        // if(NULL != pAvg)
        //     printf("%d:\t%s",i,pAvg);  

		i++; 
		printf("%d\r",i);          
    }

	top_faster_gateway();
}

// ----------------------------------- 
// 刷root (ipns --> ipfs)
#include "DarberIpfs.h"

static void refresh_gateway_body()
{

}

void refresh_gateway(const char *url,const char *ipfs)
{
	char cmd[128];

	cmd[0] = '\0';
	strcpy(cmd,"curl -L --ssl-no-revoke https://");
	strcat(cmd,url);
	strcat(cmd,ipfs);
	printf("%s\n",cmd);

	
	// 做成立刻响应返回，所以需要pthread
	// 响应体，做在 body 里即可
	// 当刷到了才退出
	// 判断刷不出就继续
}




// end of file ----------------------------------------------------------------
